//对象序列化函数
$.fn.serializeObject = function () {
    var o = {"key": "value"};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$().ready(function () {
    $("#submit").click(function(){
        // 邮箱验证相关的正则表达式
        let reg_email = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$")
        let reg_tel = new RegExp("^1\\d{10}$");

        // 序列化form表单
        let form_json = $("#login").serializeObject()

        if(check(form_json)){

            if (reg_email.test(form_json.username)) {
                // 判断邮箱登录
                form_json.email = form_json.username;
                form_json.username = "";
            } else if (reg_tel.test(form_json.username)) {
                // 电话号码登录
                form_json.tel = form_json.username;
                form_json.username = "";
            }
            // if else 过后就是用户名登录
            // 对密码进行加密
            form_json.password = hex_md5(form_json.password)

            $.post(
                // ["/login", "?redirectURL", window.location.href.split("redirectURL")[1]].join(""),
                ["/login", "?redirectURL=", $("input[name='redirectURL']").val()].join(""),
                form_json ,
                function (data) {
                    if(data.msg == "success") {
                        location.href = data.data;
                    } else {
                        alert(data.msg)
                    }
                })
            return false;
        } else {
            console.log("验证不通过！")
            return false;
            //如果不返回return是不会阻止submit的默认动作的！
        }
    });
})

//单独写一个函数判断--推荐！
var check = function(form_json){
    //用户名不为空
    let is_valid = true;
    let message = "";
    if((form_json.username == "" || form_json.username == null)){
        message = "用户名不能为空";
        is_valid = false
    }

    // 密码不能为空
    if (form_json.password == "" || form_json.password == null){
        message = "密码不能为空";
        is_valid = false;
    }

    if (!is_valid) {
        $(".login-title").text(message);
        $(".login-title").css("border", "1px solid #ffb4a8");
        $(".login-title").css("background-color", "#fef2f2");
        $(".login-title").css("color", "#6C6C6C");
        $(".login-title").css("font-size", "12px");
        $(".login-title").css("line-height", "18px");
        $(".login-title").css("padding-left", "10px");
    }

    return is_valid;
}